package com.qmrssreader.reader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.qmrssreader.reader.R;
import com.qmrssreader.dto.GroupItem;
import com.qmrssreader.dto.RssItem;
import com.qmrssreader.system.CommonConfig;
import com.qmrssreader.system.DBAdapter;
import com.qmrssreader.system.ReallySimpleReader;
public class ManageActivity extends Activity implements Runnable {

	private ListView mainListView;
	private ArrayAdapter<GroupItem> listAdapter;
	private ArrayList<GroupItem> groupList;

	private DBAdapter mDB;
	private Cursor mCursor;

	Button btnMerge;
	Button btnDelete;
	Button btnAdd;
	Button btnBack;
	Button btnDeleteAll;
	Button btnMin;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
		setContentView(R.layout.merge_feed);
		btnMerge = (Button) findViewById(R.id.btnMerge);
		btnDelete = (Button) findViewById(R.id.btnDel);
		btnDeleteAll = (Button) findViewById(R.id.btnDelAll);
		btnAdd = (Button) findViewById(R.id.btnAddF);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnMin=(Button)findViewById(R.id.btnMin);
		
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(CommonConfig.DIALOG_PROGRESS);
		progressDialog.setCancelable(false);
		progressDialog.show();

		Thread thread = new Thread(this);
		thread.start();
	}

	private void DisplayList() {

		mainListView = (ListView) findViewById(R.id.lst_group_feed);
		listAdapter = new EmployeeArrayAdapter(this, groupList);
		mainListView.setAdapter(listAdapter);

		btnMerge.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int count = 0;
				int i = 0;
				boolean flag = true;
				while (i < groupList.size()) {
					if (groupList.get(i).isChecked() == true) {
						if (groupList.get(i).getName().startsWith(CommonConfig.MERGE_GROUP_PREFIX)) {
							flag = false;
							break;
						}
						count++;
					}
					i++;
				}

				if (flag) {
					if (count < 2) {
						showDialog(CommonConfig.DIALOG_INVALID_MERGE);
					} else
						showDialog(CommonConfig.DIALOG_GOURP_NAME);
				} else {
					showDialog(CommonConfig.DIALOG_INVALID_MERGE_GROUP);
				}
			}
		});

		btnAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(CommonConfig.DIALOG_NEW_RSS);
			}
		});

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				finish();
			}
		});
		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showDialog(CommonConfig.DIALOG_DELGROUP_CONFIRM);
			}
		});
		btnDeleteAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(CommonConfig.DIALOG_DELALL_CONFIRM);

			}
		});
		btnMin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			showDialog(CommonConfig.DIALOG_TIME_CHANGE);	
			}
		});
	}

	private class EmployeeViewHolder {
		private CheckBox checkBox;
		private TextView textView;

		public EmployeeViewHolder(TextView textView, CheckBox checkBox) {
			this.checkBox = checkBox;
			this.textView = textView;

			this.textView.setOnLongClickListener(longLst);
		}

		public CheckBox getCheckBox() {
			return checkBox;
		}

		public TextView getTextView() {
			return textView;
		}

		OnLongClickListener longLst = new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				/*
				 * Intent i = new Intent(v.getContext(), MergeFeed.class);
				 * i.putExtra(Intent.EXTRA_TEXT, textView.getText().toString());
				 * startActivity(i);
				 */
				return false;
			}
		};

	}

	ReallySimpleReader rssR;
	ArrayList<RssItem> newItems = new ArrayList<RssItem>();

	public boolean addFeed(String uri) {
		if (mDB.existsURL(uri)) {
			Toast.makeText(this, CommonConfig.RSS_LINK_EXISTS,
					Toast.LENGTH_LONG).show();
			return false;
		}
		rssR = new ReallySimpleReader(uri);
		newItems = rssR.getRSSItems1();
		if (newItems == null) {
			Toast.makeText(ManageActivity.this, CommonConfig.CONNECT_URL_FAILED,
					Toast.LENGTH_LONG).show();
			return false;
		}

		String name = rssR.getTitle().trim();
		GroupItem item = new GroupItem();
		item.setName(name);
		item.setLink(uri);
		item.setChecked(false);
		int index = 0;
		int size = QMRssReaderActivity.group.size();
		if (size > 0) {
			while (index < size
					&& !QMRssReaderActivity.group.get(index).getName()
							.startsWith(CommonConfig.MERGE_GROUP_PREFIX)
					&& QMRssReaderActivity.group.get(index).getName()
							.compareToIgnoreCase(name) < 0)
				index++;

		}
		QMRssReaderActivity.group.add(index,
				new GroupItem(name, uri, rssR.getPubDate()));
		QMRssReaderActivity.children.add(index, newItems);
		groupList.add(index, item);
		mDB.createRss(name, uri);
		return true;
	}

	public void readMergedFeed(String name, String uri) {
		ArrayList<RssItem> vectParse = new ArrayList<RssItem>();
		String[] links = uri.split(CommonConfig.SPLIT_CHARACTER);
		Date pub = new Date(0);
		for (String link : links) {
			try {
				FileInputStream istream = openFileInput(link);
				DocumentBuilder builder = DocumentBuilderFactory.newInstance()
						.newDocumentBuilder();

				Document doc = builder.parse(istream);
				doc.getDocumentElement().normalize();
				NodeList nList = doc.getElementsByTagName(CommonConfig.XML_ELEMENT_ITEM);
				Date date = new Date(doc.getElementsByTagName(CommonConfig.XML_ELEMENT_PUBDATE)
						.item(0).getTextContent());
				if (date.after(pub))
					pub = date;
				// System.out.println();

				for (int temp = 0; temp < nList.getLength(); temp++) {

					Node nNode = nList.item(temp);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						// .out.println("" + temp);
						RssItem objBean;
						Element eElement = (Element) nNode;

						objBean = new RssItem();
						vectParse.add(objBean);

						Element _titleE = (Element) eElement
								.getElementsByTagName(CommonConfig.XML_ELEMENT_TITLE).item(0);
						Element _descriptionE = (Element) eElement
								.getElementsByTagName(CommonConfig.XML_ELEMENT_DESCRIPTION).item(0);
						Element _pubDateE = (Element) eElement
								.getElementsByTagName(CommonConfig.XML_ELEMENT_PUBDATE).item(0);
						Element _linkE = (Element) eElement
								.getElementsByTagName(CommonConfig.XML_ELEMENT_LINK).item(0);

						objBean.setTitle(_titleE.getFirstChild().getNodeValue());
						/*
						 * String noHTMLString = _descriptionE.getFirstChild()
						 * .getNodeValue(); noHTMLString =
						 * noHTMLString.replaceAll("\\<.*?\\>", "");
						 * objBean.setDescription(noHTMLString);
						 */
						objBean.setDescription(_descriptionE.getTextContent());
						objBean.setLink(_linkE.getFirstChild().getNodeValue());
						Date _pubDate = new Date(_pubDateE.getFirstChild()
								.getNodeValue());
						objBean.setPubDate(_pubDate);
					}

				}
				istream.close();
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
		newItems = vectParse;
		Collections.sort(newItems);
		// add merged feed vao dung thu tu
		int index = 0;
		int size = QMRssReaderActivity.group.size();
		if (size > 0) {
			while (index < size
					&& !QMRssReaderActivity.group.get(index).getName()
							.startsWith(CommonConfig.MERGE_GROUP_PREFIX))
				index++;
			while (index < size
					&& QMRssReaderActivity.group.get(index).getName()
							.compareToIgnoreCase(name) < 0)
				index++;
		}
		QMRssReaderActivity.children.add(index, newItems);
		// groups.add(name);
		QMRssReaderActivity.group.add(index, new GroupItem(name, uri, pub));
		groupList.add(index, new GroupItem(name, uri, false));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CommonConfig.DIALOG_NEW_RSS:
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.dialog_new_rss,
					null);

			return new AlertDialog.Builder(ManageActivity.this)
					.setTitle(CommonConfig.DIALOG_NEW_RSS_TITILE)
					.setView(textEntryView)
					.setIcon(R.drawable.dialog_question)
					.setPositiveButton("Add",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked OK so do some stuff */
									progressDialog.show();
									EditText txtLink = (EditText) textEntryView
											.findViewById(R.id.txtNewRssLink);
									final String link = txtLink.getText()
											.toString();
									Thread thrd = new Thread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Looper.prepare();
											addFeed(link);
											handler.sendEmptyMessage(1);
											Looper.loop();
										}
									});
									thrd.start();
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked cancel so do some stuff */
								}
							}).create();
		case CommonConfig.DIALOG_DELGROUP_CONFIRM:
			return new AlertDialog.Builder(ManageActivity.this)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setTitle(CommonConfig.DIALOG_DELETE_ALL_CHECKED_TITLE)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									progressDialog.show();
									Thread delThread = new Thread(
											new Runnable() {

												@Override
												public void run() {
													// TODO Auto-generated
													// method stub
													Looper.prepare();

													int i = 0;
													while (i < groupList.size()) {
														GroupItem item = groupList
																.get(i);
														if (item.isChecked()) {
															mDB.deleteRss(item
																	.getName());
															deleteFile(item
																	.getName());
															groupList
																	.remove(item);
															QMRssReaderActivity.children
																	.remove(i);
															QMRssReaderActivity.group
																	.remove(i);
														} else
															i++;
													}

													handler.sendEmptyMessage(3);
													Looper.loop();
												}
											});
									delThread.start();

								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked Cancel so do some stuff */
								}
							}).create();
		case CommonConfig.DIALOG_DELALL_CONFIRM:
			return new AlertDialog.Builder(ManageActivity.this)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setTitle(CommonConfig.DIALOG_DELETE_ALL_TITLE)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									QMRssReaderActivity.children.clear();
									QMRssReaderActivity.group.clear();
									mDB.deleteAllRss();
									for (String s : fileList()) {
										deleteFile(s);
									}
									groupList.clear();
									listAdapter.notifyDataSetChanged();
									Toast.makeText(ManageActivity.this,
											"Completed!!!", Toast.LENGTH_LONG)
											.show();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked Cancel so do some stuff */
								}
							}).create();
		case CommonConfig.DIALOG_GOURP_NAME:

			final EditText txtGroupName = new EditText(this);
			txtGroupName.setHint("Name");
			return new AlertDialog.Builder(ManageActivity.this)
					.setTitle(CommonConfig.DIALOG_NEW_MERGE_RSS_TITILE)
					.setView(txtGroupName)
					.setIcon(R.drawable.dialog_question)
					.setPositiveButton("Add",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked OK so do some stuff */
									final String name = "QM - "
											+ txtGroupName.getText().toString();
									if (mDB.existsName(name)) {
										Toast.makeText(ManageActivity.this,
												CommonConfig.RSS_NAME_EXISTS,
												Toast.LENGTH_LONG).show();
										// handler.sendEmptyMessage(4);
										return;
									}

									progressDialog.show();
									Thread thrd = new Thread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Looper.prepare();
											// ArrayList<GroupItem> lstSubItems
											// = new ArrayList<GroupItem>();

											StringBuilder link = new StringBuilder(
													groupList.get(0).getName());
											for (int i = 1; i < groupList
													.size(); i++) {
												GroupItem item = groupList
														.get(i);
												if (item.isChecked()) {
													// lstSubItems.add(item);
													link.append(CommonConfig.SPLIT_CHARACTER);
													link.append(item.getName());
												}
											}
											/*
											 * GroupItem newG = new GroupItem(
											 * name, link.toString(), false);
											 * groupList.add(newG);
											 */
											mDB.createRss(name, link.toString());
											readMergedFeed(name,
													link.toString());
											handler.sendEmptyMessage(2);
											Toast.makeText(ManageActivity.this,
													CommonConfig.SUCCESSFUL,
													Toast.LENGTH_LONG).show();
											Looper.loop();
										}
									});
									thrd.start();
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked cancel so do some stuff */
								}
							}).create();
		case CommonConfig.DIALOG_INVALID_MERGE:
			return new AlertDialog.Builder(ManageActivity.this)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setTitle(CommonConfig.DIALOG_INVALID_MERGE_TITLE)
					.setPositiveButton("Close",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		case CommonConfig.DIALOG_INVALID_MERGE_GROUP:
			return new AlertDialog.Builder(ManageActivity.this)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setTitle(CommonConfig.DIALOG_INVALID_MERGE_GROUP_TITLE)
					.setPositiveButton("Close",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									for (int i = 0; i < groupList.size(); i++) {
										if (groupList.get(i).isChecked()) {
											groupList.get(i).setChecked(false);
										}
									}
									listAdapter.notifyDataSetChanged();
								}
							}).create();
		case CommonConfig.DIALOG_TIME_CHANGE:
			LayoutInflater factory1 = LayoutInflater.from(this);
			final View v = factory1.inflate(R.layout.dialog_time_change,
					null);
			return new AlertDialog.Builder(ManageActivity.this)
					.setTitle(CommonConfig.DIALOG_TIME_CHANGE_TITILE)
					.setView(v)
					.setIcon(R.drawable.dialog_question)
					.setPositiveButton("Add",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked OK so do some stuff */
									EditText txtTime=(EditText)v.findViewById(R.id.txtTime);
									String temp=txtTime.getText().toString();
									
										CommonConfig.min_of_check=Integer.valueOf(temp);
										Toast.makeText(ManageActivity.this,
												CommonConfig.SUCCESSFUL,
												Toast.LENGTH_LONG).show();
										try {
											FileOutputStream fos=openFileOutput("config.ini", MODE_PRIVATE);
											fos.write(temp.getBytes());
											fos.close();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked cancel so do some stuff */
								}
							}).create();
		}
		return null;
	}
	public static boolean isNumeric(String str)
	 {
	    return str.matches("-?\\d+(.\\d+)?");
	  }
	private ArrayList<GroupItem> getData() {
		mCursor = mDB.getAllRss1();
		startManagingCursor(mCursor);
		ArrayList<GroupItem> lstEmployee = new ArrayList<GroupItem>();
		while (mCursor.moveToNext()) {
			if (!mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_NAME)).startsWith(
					"QM")) {
				GroupItem emp = new GroupItem();
				emp.setName(mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_NAME)));
				emp.setLink(mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_LINK)));
				lstEmployee.add(emp);
			}
		}
		mCursor = mDB.getAllRss2();
		while (mCursor.moveToNext()) {
			GroupItem emp = new GroupItem();
			emp.setName(mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_NAME)));
			emp.setLink(mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_LINK)));
			lstEmployee.add(emp);
		}

		return lstEmployee;
	}

	private class EmployeeArrayAdapter extends ArrayAdapter<GroupItem> {

		private LayoutInflater inflater;

		public EmployeeArrayAdapter(Context context, List<GroupItem> planetList) {
			super(context, R.layout.simplerow, R.id.rowTextView, planetList);

			inflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			GroupItem empl = (GroupItem) this.getItem(position);
			CheckBox checkBox;
			TextView textView;
			// Create a new row view
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.simplerow, null);

				// Find the child views.
				textView = (TextView) convertView
						.findViewById(R.id.rowTextView);
				checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
				convertView.setTag(new EmployeeViewHolder(textView, checkBox));

				checkBox.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						CheckBox cb = (CheckBox) v;
						GroupItem employee1 = (GroupItem) cb.getTag();
						employee1.setChecked(cb.isChecked());
					}
				});
			}

			else {
				EmployeeViewHolder viewHolder = (EmployeeViewHolder) convertView
						.getTag();
				checkBox = viewHolder.getCheckBox();
				textView = viewHolder.getTextView();
			}
			checkBox.setTag(empl);

			checkBox.setChecked(empl.isChecked());
			textView.setText(empl.getName());
			return convertView;
		}

	}

	@Override
	public void run() {
		Looper.prepare();
		mDB = new DBAdapter(this);
		mDB.open();
		groupList = getData();
		handler.sendEmptyMessage(0);
		Looper.loop();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message message) {
			switch (message.what) {
			case 0:
				progressDialog.dismiss();
				DisplayList();
				break;
			case 1:
				progressDialog.dismiss();
				listAdapter.notifyDataSetChanged();
				break;
			case 2:
				progressDialog.dismiss();
				for (int i = 0; i < groupList.size(); i++) {
					if (groupList.get(i).isChecked()) {
						groupList.get(i).setChecked(false);
					}
				}
				listAdapter.notifyDataSetChanged();
				break;
			case 3:
				progressDialog.dismiss();
				listAdapter.notifyDataSetChanged();
				break;
			case 4:
				progressDialog.dismiss();
				Toast.makeText(ManageActivity.this, CommonConfig.RSS_NAME_EXISTS,
						Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		}

	};
}